/*
 * This program is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Affero General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3, 
 * the Appropriate Legal Notices must display the following words on all interactive user interfaces: 
 * "Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved."
 */

var sDETAILVIEW_MODULE  = null;
var sDETAILVIEW_ID      = null;

function DetailViewUI_PageCommand(sLayoutPanel, sActionsPanel, sCommandName, sCommandArguments)
{
	try
	{
		if ( sCommandName == 'Edit' )
		{
			EditViewUI_Load(sLayoutPanel, sActionsPanel, sDETAILVIEW_MODULE, sDETAILVIEW_ID, false);
			sDETAILVIEW_MODULE  = null;
			sDETAILVIEW_ID      = null;
		}
		else if ( sCommandName == 'Duplicate' )
		{
			EditViewUI_Load(sLayoutPanel, sActionsPanel, sDETAILVIEW_MODULE, sDETAILVIEW_ID, true);
			sDETAILVIEW_MODULE  = null;
			sDETAILVIEW_ID      = null;
		}
		else if ( sCommandName == 'Delete' )
		{
			var bgPage = chrome.extension.getBackgroundPage();
			bgPage.DeleteModuleItem(sDETAILVIEW_MODULE, sDETAILVIEW_ID, function(status, message)
			{
				if ( status == 1 )
				{
					var sGRID_NAME = sDETAILVIEW_MODULE + '.ListView' + sPLATFORM_LAYOUT;
					ListViewUI_Reset(sLayoutPanel, sDETAILVIEW_MODULE);
					ListViewUI_Load(sLayoutPanel, sActionsPanel, sDETAILVIEW_MODULE, sGRID_NAME, null, function(status, message)
					{
						if ( status == 0 || status == 1 )
						{
							sDETAILVIEW_MODULE  = null;
							sDETAILVIEW_ID      = null;
						}
					});
				}
				else
				{
					SplendidError.SystemMessage(message);
				}
			});
		}
		else if ( sCommandName == 'ViewLog' )
		{
			SplendidError.SystemMessage('ViewLog not supported');
		}
		else if ( sCommandName == 'Cancel' )
		{
			var sGRID_NAME = sDETAILVIEW_MODULE + '.ListView' + sPLATFORM_LAYOUT;
			ListViewUI_Reset(sLayoutPanel, sDETAILVIEW_MODULE);
			ListViewUI_Load(sLayoutPanel, sActionsPanel, sDETAILVIEW_MODULE, sGRID_NAME, null, function(status, message)
			{
				if ( status == 0 || status == 1 )
				{
					sDETAILVIEW_MODULE  = null;
					sDETAILVIEW_ID      = null;
				}
			});
		}
		else
		{
			SplendidError.SystemMessage('DetailViewUI_PageCommand: Unknown command ' + sCommandName);
		}
	}
	catch(e)
	{
		SplendidError.SystemError(e, 'DetailViewUI_PageCommand');
	}
}

function DetailViewUI_Clear(sLayoutPanel)
{
	try
	{
		var divMainLayoutPanel = document.getElementById(sLayoutPanel);
		if ( divMainLayoutPanel != null && divMainLayoutPanel.childNodes != null )
		{
			while ( divMainLayoutPanel.childNodes.length > 0 )
			{
				divMainLayoutPanel.removeChild(divMainLayoutPanel.firstChild);
			}
		}
		if ( divMainLayoutPanel == null )
		{
			alert('DetailViewUI_Clear: ' + sLayoutPanel + ' does not exist');
			return;
		}
		// <table id="ctlDetailView_tblMain" class="tabDetailView">
		var ctlDetailView_tblMain = document.createElement('table');
		ctlDetailView_tblMain.id        = sLayoutPanel + '_ctlDetailView_tblMain';
		ctlDetailView_tblMain.width     = '100%';
		ctlDetailView_tblMain.className = 'tabDetailView';
		divMainLayoutPanel.appendChild(ctlDetailView_tblMain);
	}
	catch(e)
	{
		SplendidError.SystemAlert(e, 'DetailViewUI_Clear');
	}
}

function DetailViewUI_LoadView(sLayoutPanel, sActionsPanel, tblMain, layout, row)
{
	try
	{
		var tbody = document.createElement('tbody');
		tblMain.appendChild(tbody);
		
		var tr = null;
		var nColumn = 0;
		var bEnableTeamManagement = Crm.Config.enable_team_management();
		var bEnableDynamicTeams   = Crm.Config.enable_dynamic_teams();
		for ( var nLayoutIndex in layout )
		{
			var lay = layout[nLayoutIndex];
			var sFIELD_TYPE   = lay.FIELD_TYPE  ;
			var sDATA_LABEL   = lay.DATA_LABEL  ;
			var sDATA_FIELD   = lay.DATA_FIELD  ;
			var sDATA_FORMAT  = lay.DATA_FORMAT ;
			var sURL_FIELD    = lay.URL_FIELD   ;
			var sURL_FORMAT   = lay.URL_FORMAT  ;
			var sURL_TARGET   = lay.URL_TARGET  ;
			var sLIST_NAME    = lay.LIST_NAME   ;
			var nCOLSPAN      = Sql.ToInteger(lay.COLSPAN);
			var sLABEL_WIDTH  = lay.LABEL_WIDTH ;
			var sFIELD_WIDTH  = lay.FIELD_WIDTH ;
			var sDATA_COLUMNS = lay.DATA_COLUMNS;
			var sVIEW_NAME    = lay.VIEW_NAME   ;
			var sMODULE_NAME  = lay.MODULE_NAME ;
			var sTOOL_TIP     = lay.TOOL_TIP    ;
			var sMODULE_TYPE  = lay.MODULE_TYPE ;
			var sPARENT_FIELD = lay.PARENT_FIELD;
			
			if ( (sDATA_FIELD == 'TEAM_NAME' || sDATA_FIELD == 'TEAM_SET_NAME') )
			{
				if ( !bEnableTeamManagement )
				{
					sFIELD_TYPE = 'Blank';
				}
				else if ( bEnableDynamicTeams )
				{
					sDATA_LABEL = '.LBL_TEAM_SET_NAME';
					sDATA_FIELD = 'TEAM_SET_NAME';
				}
			}
			if ( sDATA_FIELD == 'EXCHANGE_FOLDER' )
			{
				if ( !Crm.Modules.ExchangeFolders(sMODULE_NAME) )
				{
					sFIELD_TYPE = 'Blank';
				}
			}
			if ( nColumn % 2 == 0 || tr == null )
			{
				tr = document.createElement('tr');
				tbody.appendChild(tr);
			}
			var tdLabel = document.createElement('td');
			tr.appendChild(tdLabel);
			tdLabel.className = 'tabDetailViewDL';
			tdLabel.vAlign    = 'top';
			tdLabel.width     = sLABEL_WIDTH;
			if ( sDATA_LABEL != null )
			{
				if ( sFIELD_TYPE != 'Blank' )
				{
					var txt = document.createTextNode(L10n.Term(sDATA_LABEL));
					tdLabel.appendChild(txt);
				}
			}
			
			var tdField = document.createElement('td');
			tr.appendChild(tdField);
			tdField.className = 'tabDetailViewDF';
			tdField.vAlign    = 'top';
			tdField.width     = sFIELD_WIDTH;
			tdField.id        = tblMain.id + '_' + sDATA_FIELD;
			if ( nCOLSPAN > 0 )
			{
				tdField.colSpan = nCOLSPAN;
				nColumn++;
			}
			if ( sFIELD_TYPE == 'HyperLink' )
			{
				if ( row[sDATA_FIELD] != null && sURL_FORMAT != null && sDATA_FORMAT != null )
				{
					var a = document.createElement('a');
					tdField.appendChild(a);
					if ( sURL_FORMAT.substr(0, 2) == '~/' )
					{
						var arrURL_FORMAT = sURL_FORMAT.split('/');
						var sURL_MODULE_NAME = sMODULE_NAME;
						if ( arrURL_FORMAT.length > 1 )
							sURL_MODULE_NAME = arrURL_FORMAT[1];
						a.href = 'javascript:DetailViewUI_Load("' + sLayoutPanel + '", "' + sActionsPanel + '", "' + sURL_MODULE_NAME + '", "' + row[sURL_FIELD] + '")';
					}
					else
					{
						a.href = sURL_FORMAT.replace('{0}', row[sURL_FIELD]);
					}
					a.innerHTML = sDATA_FORMAT.replace('{0}', row[sDATA_FIELD]);
				}
			}
			else if ( sFIELD_TYPE == 'String' )
			{
				if ( sDATA_FORMAT != null )
				{
					try
					{
						if ( sDATA_FORMAT.indexOf(' ') > 0 )
						{
							var arrDATA_FORMAT = sDATA_FORMAT.split(' ');
							var arrDATA_FIELD  = sDATA_FIELD.split(' ');
							for ( var nFormatIndex = 0; nFormatIndex < arrDATA_FIELD.length; nFormatIndex++ )
							{
								if ( arrDATA_FIELD[nFormatIndex].indexOf('.') >= 0 )
								{
									sDATA_FORMAT = sDATA_FORMAT.replace('{' + nFormatIndex.toString() + '}', L10n.Term(arrDATA_FIELD[nFormatIndex]));
								}
								else
								{
									//alert(arrDATA_FIELD[nFormatIndex] + ' ' + row[arrDATA_FIELD[nFormatIndex]]);
									if ( row[arrDATA_FIELD[nFormatIndex]] == null )
									{
										sDATA_FORMAT = sDATA_FORMAT.replace('{' + nFormatIndex.toString() + '}', '');
									}
									else
									{
										var sDATA_VALUE = row[arrDATA_FIELD[nFormatIndex]];
										sDATA_VALUE = FromJsonDate(sDATA_VALUE, Security.USER_DATE_FORMAT() + ' ' + Security.USER_TIME_FORMAT());
										//alert(row[arrDATA_FIELD[nFormatIndex]] + ' = ' + sDATA_VALUE);
										sDATA_FORMAT = sDATA_FORMAT.replace('{' + nFormatIndex.toString() + '}', sDATA_VALUE);
									}
								}
							}
							tdField.id = sDATA_FIELD.replace(' ', '_');
							tdField.innerHTML = sDATA_FORMAT;
						}
						else if ( row[sDATA_FIELD] != null )
						{
							tdField.id = sDATA_FIELD.replace(' ', '_');
							if ( sLIST_NAME != null )
							{
								var sDATA_VALUE = L10n.Term('.' + sLIST_NAME + '.' + row[sDATA_FIELD]);
								// 10/04/2011 Paul.  Testing for NULL does not work, so just check if the list name matches the label. 
								if ( sDATA_VALUE == '.' + sLIST_NAME + '.' )
									sDATA_VALUE = '';
								tdField.innerHTML = sDATA_FORMAT.replace('{0}', sDATA_VALUE);
							}
							else
							{
								var sDATA_VALUE = row[sDATA_FIELD];
								try
								{
									if ( sDATA_FORMAT.indexOf('{0:d}') >= 0 )
									{
										sDATA_VALUE = FromJsonDate(sDATA_VALUE, Security.USER_DATE_FORMAT());
										tdField.innerHTML = sDATA_FORMAT.replace('{0:d}', sDATA_VALUE);
									}
									else if ( sDATA_FORMAT.indexOf('{0:c}') >= 0 )
									{
										tdField.innerHTML = sDATA_FORMAT.replace('{0:c}', sDATA_VALUE);
									}
									// 10/03/2011 Paul.  If the data value is an integer, then substr() will throw an exception. 
									else if ( typeof(sDATA_VALUE) == 'string' && sDATA_VALUE.substr(0, 7) == '\\/Date(' )
									{
										sDATA_VALUE = FromJsonDate(sDATA_VALUE, Security.USER_DATE_FORMAT() + ' ' + Security.USER_TIME_FORMAT());
										tdField.innerHTML = sDATA_FORMAT.replace('{0}', sDATA_VALUE);
									}
									else
									{
										tdField.innerHTML = sDATA_FORMAT.replace('{0}', sDATA_VALUE);
									}
								}
								catch(e)
								{
									//alert(dumpObj(sDATA_VALUE, e.message));
								}
							}
						}
					}
					catch(e)
					{
						SplendidError.SystemAlert(e, 'DetailViewUI_LoadView');
					}
				}
			}
			else if ( sFIELD_TYPE == 'TextBox' )
			{
				if ( row[sDATA_FIELD] != null )
				{
					tdField.id = sDATA_FIELD.replace(' ', '_');
					tdField.innerHTML = row[sDATA_FIELD];
				}
			}
			else if ( sFIELD_TYPE == 'CheckBox' )
			{
				var chk = document.createElement('input');
				// 06/18/2011 Paul.  IE requires that the input type be defined prior to appending the field. 
				chk.id        = sDATA_FIELD.replace(' ', '_');
				chk.type      = 'checkbox';
				chk.className = 'checkbox';
				chk.disabled  = 'disabled';
				// 09/25/2011 Paul.  IE does not allow you to set the type after it is added to the document. 
				tdField.appendChild(chk);
				chk.checked   = Sql.ToBoolean(row[sDATA_FIELD]);
			}
			else if ( sFIELD_TYPE == 'Blank' )
			{
				tdField.innerHTML = '';
			}
			else
			{
				tdField.innerHTML = 'Unsupported field type: ' + sFIELD_TYPE;
			}
			nColumn++;
		}
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'DetailViewUI_LoadView'));
	}
}

function DetailViewUI_LoadItem(sLayoutPanel, sActionsPanel, layout, sDETAIL_NAME, sMODULE_NAME, sID, callback)
{
	try
	{
		var bgPage = chrome.extension.getBackgroundPage();
		bgPage.DetailView_LoadItem(sMODULE_NAME, sID, function(status, message)
		{
			if ( status == 1 )
			{
				// 10/04/2011 Paul.  DetailViewUI_LoadItem returns the row. 
				var row = message;
				DynamicButtonsUI_Clear(sActionsPanel);
				DetailViewUI_Clear(sLayoutPanel);
				TabMenuUI_ActivateTab(sMODULE_NAME);
				SplendidUI_ModuleHeader(sLayoutPanel, sActionsPanel, sMODULE_NAME, Sql.ToString(row['NAME']));
				DynamicButtonsUI_Load(sLayoutPanel, sActionsPanel, sDETAIL_NAME, row, DetailViewUI_PageCommand, function(status, message)
				{
					if ( status != 1 )
						callback(status, message);
				});
				
				//var layout = bgPage.SplendidCache.DetailViewFields(sDETAIL_NAME);
				var tblMain = document.getElementById(sLayoutPanel + '_ctlDetailView_tblMain');
				DetailViewUI_LoadView(sLayoutPanel, sActionsPanel, tblMain, layout, row);
			}
			else
			{
				callback(status, message);
			}
		});
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'DetailViewUI_LoadItem'));
	}
}

function DetailViewUI_LoadObject(sLayoutPanel, sActionsPanel, sDETAIL_NAME, sMODULE_NAME, row, PageCommand, callback)
{
	try
	{
		sDETAILVIEW_MODULE  = sMODULE_NAME;
		sDETAILVIEW_ID      = null;
		
		var bgPage = chrome.extension.getBackgroundPage();
		bgPage.Terminology_LoadModule(sMODULE_NAME, function(status, message)
		{
			if ( status == 0 || status == 1 )
			{
				bgPage.DetailView_LoadLayout(sDETAIL_NAME, function(status, message)
				{
					if ( status == 1 )
					{
						// 10/03/2011 Paul.  DetailView_LoadLayout returns the layout. 
						var layout = message;
						if ( row != null )
						{
							DynamicButtonsUI_Clear(sActionsPanel);
							DetailViewUI_Clear(sLayoutPanel);
							
							if ( PageCommand == null )
								PageCommand = DetailViewUI_PageCommand;
							DynamicButtonsUI_Load(sLayoutPanel, sActionsPanel, sDETAIL_NAME, row, PageCommand, function(status, message)
							{
							});
							
							//var layout = bgPage.SplendidCache.DetailViewFields(sDETAIL_NAME);
							var tblMain = document.getElementById(sLayoutPanel + '_ctlDetailView_tblMain');
							DetailViewUI_LoadView(sLayoutPanel, sActionsPanel, tblMain, layout, row);
							
							callback(status, message);
						}
					}
					else
					{
						callback(status, message);
					}
				});
			}
			else
			{
				callback(status, message);
			}
		});
	}
	catch(e)
	{
		callback(-1, SplendidError.FormatError(e, 'DetailViewUI_LoadObject'));
	}
}

function DetailViewUI_Load(sLayoutPanel, sActionsPanel, sMODULE_NAME, sID)
{
	try
	{
		sDETAILVIEW_MODULE  = null;
		sDETAILVIEW_ID      = null;
		
		var bgPage = chrome.extension.getBackgroundPage();
		// 11/29/2011 Paul.  We are having an issue with the globals getting reset, so we need to re-initialize. 
		if ( !bgPage.SplendidCache.IsInitialized() )
		{
			SplendidUI_ReInit(sLayoutPanel, sActionsPanel, sMODULE_NAME);
			return;
		}
		
		sDETAILVIEW_MODULE  = sMODULE_NAME;
		sDETAILVIEW_ID      = sID;
		// 10/04/2011 Paul.  The session might have timed-out, so first check if we are authenticated. 
		bgPage.AuthenticatedMethod(function(status, message)
		{
			if ( status == 1 )
			{
				bgPage.Terminology_LoadModule(sMODULE_NAME, function(status, message)
				{
					if ( status == 0 || status == 1 )
					{
						var sDETAIL_NAME = sMODULE_NAME + '.DetailView' + sPLATFORM_LAYOUT;
						bgPage.DetailView_LoadLayout(sDETAIL_NAME, function(status, message)
						{
							if ( status == 1 )
							{
								SplendidUI_ModuleHeader(sLayoutPanel, sActionsPanel, sMODULE_NAME, '');
								// 10/03/2011 Paul.  DetailView_LoadLayout returns the layout. 
								var layout = message;
								if ( sID != null )
								{
									DetailViewUI_LoadItem(sLayoutPanel, sActionsPanel, layout, sDETAIL_NAME, sMODULE_NAME, sID, function(status, message)
									{
										if ( status == 1 )
										{
											SplendidError.SystemMessage('');
										}
										else
										{
											SplendidError.SystemMessage(message);
										}
									});
								}
							}
							else
							{
								SplendidError.SystemMessage(message);
							}
						});
					}
					else
					{
						SplendidError.SystemMessage(message);
					}
				});
			}
			else
			{
				SplendidError.SystemMessage(message);
			}
		});
	}
	catch(e)
	{
		SplendidError.SystemError(e, 'DetailViewUI_Load');
	}
}


